<template>
  <div class="mobile-order-list">
    <!-- 筛选表单 -->
    <div class="filter-form">
      <el-form :model="formParams" size="small" label-width="80px">
        <el-form-item label="订单号">
          <el-input v-model="formParams.orderNumber" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="formParams.email" placeholder="请输入邮箱" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="formParams.status" placeholder="请选择订单状态" clearable style="width: 100%">
            <el-option label="所有状态" value=""></el-option>
            <el-option label="待发货" value="2"></el-option>
            <el-option label="待收货" value="4"></el-option>
            <el-option label="已完成" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流状态">
          <el-select v-model="formParams.logisticsStatus" placeholder="请选择物流状态" clearable style="width: 100%">
            <el-option label="所有状态" value=""></el-option>
            <el-option label="待发货" value="1"></el-option>
            <el-option label="部分发货" value="2"></el-option>
            <el-option label="全部发货" value="3"></el-option>
            <el-option label="全部确认" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            style="width: 100%"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" style="margin-right: 10px">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <div class="order-list">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else-if="orderList.length === 0" class="empty-container">
        <empty v-if="orderList.length === 0"/>
      </div>
      <div v-else>
        <div v-for="(order, index) in orderList" :key="index" class="order-item" @click="handleDetail(order.id)">
          <div class="order-header">
            <div class="order-number">订单号: {{ order.orderNumber }}</div>
            <div class="order-status" :class="getStatusClass(order.statusText)">{{ order.statusText }}</div>
          </div>
          <div class="order-info">
            <div class="info-item">
              <span class="label">下单邮箱:</span>
              <span class="value">{{ order.email }}</span>
            </div>
            <div class="info-item">
              <span class="label">订单金额:</span>
              <span class="value">{{ formatCurrency(order.payAmount, order.currencySymbol) }}</span>
            </div>
            <div class="info-item">
              <span class="label">下单时间:</span>
              <span class="value">{{ formatDate(order.createDate) }}</span>
            </div>
            <div class="info-item">
              <span class="label">商品数:</span>
              <span class="value">{{ order.totalItemNum }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付方式:</span>
              <span class="value">{{ order.payType }}</span>
            </div>
            <div class="info-item">
              <span class="label">物流状态:</span>
              <span class="value" :class="getStatusClass(order.logisticsStatusText)">{{ order.logisticsStatusText }}</span>
            </div>
            <div class="info-item">
              <span class="label">国家/地区:</span>
              <span class="value">{{ order.country }}</span>
            </div>
            <div class="info-item">
              <span class="label">确认邮件:</span>
              <span class="value" :class="order.confirmEmail ? 'success' : 'danger'">
                {{ order.confirmEmail ? '已发送' : '未发送' }}
              </span>
            </div>
          </div>
          <div class="order-actions">
            <el-button size="small" type="primary" @click.stop="handleConfirmEmail(order.id)">发送确认邮件</el-button>
          </div>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="formParams.page"
            :page-sizes="[20, 30, 50]"
            :page-size="formParams.pageSize"
            layout="total, prev, pager, next"
            :small="true"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getOrderPage, confirmEmail } from '@/api/order';
import { mapGetters } from 'vuex';
import { currency, utcFormat } from '@/utils/filters';

export default {
    name: 'MobileOrderList',
    props: {
        siteId: {
            type: [String, Number],
            required: true
        }
    },
    data () {
        return {
            loading: false,
            orderList: [],
            total: 0,
            dateRange: [],
            pickerOptions: {
                firstDayOfWeek: 1,
                shortcuts: [{
                    text: '最近一周',
                    onClick (picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick (picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setMonth(start.getMonth() - 1);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick (picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setMonth(start.getMonth() - 3);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            formParams: {
                siteId: this.siteId,
                status: '',
                payStatus: '',
                logisticsStatus: '',
                orderNumber: '',
                email: '',
                startTime: '',
                endTime: '',
                page: 1,
                pageSize: 20
            }
        };
    },
    computed: {
        ...mapGetters([
            'timeZone'
        ])
    },
    created () {
        this.fetchData();
    },
    methods: {
        fetchData () {
            this.loading = true;

            // 处理日期范围
            if (this.dateRange && this.dateRange.length === 2) {
                this.formParams.startTime = this.getSiteTimeZoneStartTime(this.dateRange[0]);
                this.formParams.endTime = this.getSiteTimeZoneEndTime(this.dateRange[1]);
            } else {
                this.formParams.startTime = '';
                this.formParams.endTime = '';
            }

            getOrderPage(this.formParams).then(res => {
                this.orderList = res.records || [];
                this.total = res.totalElements || 0;
                this.loading = false;
            }).catch(() => {
                this.loading = false;
            });
        },
        handleSearch () {
            this.formParams.page = 1;
            this.fetchData();
        },
        resetForm () {
            this.formParams = {
                siteId: this.siteId,
                status: '',
                payStatus: '',
                logisticsStatus: '',
                orderNumber: '',
                email: '',
                startTime: '',
                endTime: '',
                page: 1,
                pageSize: 10
            };
            this.dateRange = [];
            this.fetchData();
        },
        handleSizeChange (val) {
            this.formParams.pageSize = val;
            this.fetchData();
        },
        handleCurrentChange (val) {
            this.formParams.page = val;
            this.fetchData();
        },
        handleDetail (id) {
            this.$router.push({ name: 'order-detail', params: { id } });
        },
        handleConfirmEmail (id) {
            this.$confirm('确定要发送确认邮件吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                confirmEmail(id).then(res => {
                    if (res.code === '200') {
                        this.$message.success('发送成功');
                        setTimeout(() => {
                            this.fetchData();
                        }, 1000);
                    }
                });
            }).catch(() => {});
        },
        formatCurrency (amount, symbol) {
            return currency(amount, symbol || '$');
        },
        formatDate (date) {
            return utcFormat(date, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
        },
        getStatusClass (status) {
            const statusMap = {
                '待发货': 'status-pending',
                '待收货': 'status-shipping',
                '已完成': 'status-completed',
                '全部发货': 'status-shipped',
                '全部确认': 'status-confirmed'
            };
            return statusMap[status] || '';
        },
        getSiteTimeZoneStartTime (startTime) {
            if (startTime === undefined || startTime == null || startTime === '') {
                return startTime;
            }
            let tempTime = new Date(startTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 00:00:00 UTC' + this.timeZone;
            return new Date(timeZoneStr).getTime();
        },
        getSiteTimeZoneEndTime (endTime) {
            if (endTime === undefined || endTime == null || endTime === '') {
                return endTime;
            }
            let tempTime = new Date(endTime);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + ' 23:59:59 UTC' + this.timeZone;
            return new Date(timeZoneStr).getTime();
        }
    }
};
</script>

<style lang="scss" scoped>
.mobile-order-list {
  padding: 10px 0;

  .filter-form {
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .order-list {
    .loading-container, .empty-container {
      padding: 20px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .order-item {
      background-color: #fff;
      border-radius: 4px;
      padding: 15px;
      margin-bottom: 15px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 10px;
        border-bottom: 1px solid #ebeef5;

        .order-number {
          font-weight: bold;
          color: #409EFF;
        }

        .order-status {
          padding: 2px 8px;
          border-radius: 10px;
          font-size: 12px;

          &.status-pending {
            background-color: #fdf6ec;
            color: #e6a23c;
          }

          &.status-shipping {
            background-color: #ecf5ff;
            color: #409eff;
          }

          &.status-completed {
            background-color: #f0f9eb;
            color: #67c23a;
          }

          &.status-shipped {
            background-color: #f4f4f5;
            color: #909399;
          }

          &.status-confirmed {
            background-color: #f0f9eb;
            color: #67c23a;
          }
        }
      }

      .order-info {
        padding: 10px 0;

        .info-item {
          display: flex;
          margin-bottom: 8px;

          .label {
            width: 80px;
            color: #606266;
          }

          .value {
            flex: 1;
            color: #303133;

            &.warning {
              color: #e6a23c;
            }

            &.primary {
              color: #409eff;
            }

            &.success {
              color: #67c23a;
            }

            &.danger {
              color: #f56c6c;
            }

            &.info {
              color: #909399;
            }
          }
        }
      }

      .order-actions {
        display: flex;
        justify-content: flex-end;
        padding-top: 10px;
        border-top: 1px solid #ebeef5;
      }
    }

    .pagination-container {
      text-align: center;
      margin-top: 20px;
      padding: 15px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }
}

@media screen and (max-width: 768px) {
  .mobile-order-list {
    .pagination-container {
      .el-pagination {
        white-space: normal;

        .el-pagination__sizes {
          margin-top: 10px;
        }
      }
    }
  }
}
</style>
